package com.epoch.platform.sys.generator.service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.IOUtils;

import com.epoch.platform.sys.generator.util.GenUtils;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;

public class GeneratorService {
	
	public byte[] generatorCode(String[] tableNames) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		
		for(String tableName : tableNames){
			//查询表信息
			Record table = queryTable(tableName);
			//查询列信息
			List<Record> columns = queryColumns(tableName);
			//生成代码
			GenUtils.generatorCode(table, columns, zip);
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}
	
	public byte[] generatorCodeStart(String tableNames) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		Kv params = Kv.create();
		params.set("tableName",tableNames);
		SqlPara sqlPara = Db.getSqlPara("systemManage.findTableStart", params);
		List<Record> records = Db.find(sqlPara);
		for(Record record : records){
			//查询列信息tableName
			List<Record> columns = queryColumns(record.getStr("tableName"));
			//生成代码
			GenUtils.generatorCode(record, columns, zip);
		}
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}
	
	
	
	public byte[] generatorCode(String tableName) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		
		//查询表信息
		Record table = queryTable(tableName);
		//查询列信息
		List<Record> columns = queryColumns(tableName);
		//生成代码
		GenUtils.generatorCode(table, columns, zip);
		IOUtils.closeQuietly(zip);
		return outputStream.toByteArray();
	}

	private List<Record> queryColumns(String tableName) {
		Kv params = Kv.create();
		params.set("tableName",tableName);
		SqlPara sqlPara = Db.getSqlPara("systemManage.findColumns", params);
		List<Record> list = Db.find(sqlPara);
		return list;
	}

	private Record queryTable(String tableName) {
		Kv params = Kv.create();
		params.set("tableName",tableName);
		SqlPara sqlPara = Db.getSqlPara("systemManage.findTable", params);
		Record record = Db.findFirst(sqlPara);
		return record;
	}
}
